<template>
  <el-cascader
    class="base-area-select"
    ref="baseAreaSelect"
    v-model="cascaderValue"
    :options="datas"
    :props="propsOption"
    filterable
    clearable
    @change="changeArea"
  ></el-cascader>
</template>

<script>
import sourceData from "./areaData.json";

export default {
  name: "BaseAreaSelect",
  props: {
    value: Array,
    valueFormat: {
      // 数据源中对应的键名
      type: String,
      default: "ext_name",
    },
    adcode: String,
  },
  model: {
    prop: "value",
    event: "model-event",
  },
  data() {
    return {};
  },
  computed: {
    datas() {
      return sourceData;
    },
    cascaderValue: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("model-event", val);
      },
    },
    propsOption() {
      return {
        value: this.valueFormat,
        label: "ext_name",
        emitPath: true,
      };
    },
  },
  watch: {
    adcode(newValue, oldValue) {
      if (newValue && newValue.length === 6) {
        // 根据adcode遍历出省市区
        let result = [];
        let provinceData = null;
        let urbanData = null;
        let townshipData = null;
        // 确定省份
        const provinceId = newValue.slice(0, 2) + "0000";
        provinceData = sourceData.find((item) => item.id === provinceId);
        if (provinceData) {
          result.push((provinceData[this.valueFormat] || ""));
          urbanData = provinceData.children || [];
        }
        // 确定市区
        if (urbanData && urbanData.length) {
          const urbanId = newValue.slice(0, 4) + "00";
          let urbanDatas = urbanData.find((item) => item.id === urbanId);
          if(!urbanDatas) {  // 考虑无三级行政区域的
            urbanDatas = urbanData.find((item) => item.id === newValue);
          }
          result.push((urbanDatas[this.valueFormat] || ""));
          townshipData = (urbanDatas || {}).children || [];
        }
        // 确定乡镇
        if (townshipData && townshipData.length) {
          const township = townshipData.find((item) => item.id === newValue);
          result.push((township[this.valueFormat] || ""));
        }
        this.cascaderValue = result;
      }
    },
  },
  methods: {
    changeArea(data) {
      // change事件抛出最后一项的原始数据
      // console.log(data);
      // console.log(this.$refs.baseAreaSelect.panel.getNodeByValue(data[data.length - 1]));
      const lastSourceNode = this.$refs.baseAreaSelect.panel.getNodeByValue(
        data[data.length - 1]
      );
      // console.log(lastSourceNode);
      const lastSourceData = lastSourceNode ? lastSourceNode.data : {};
      this.$emit("update:adcode", lastSourceData.id);
      this.$emit("area-change", lastSourceData);
    },
  },
};
</script>

<style lang="scss" scoped>
.base-area-select {
  width: 100%;
}
</style>
